package listener

import (
	"io"
	"log"
	"serial-port-go/lib/utils"
	"serial-port-go/src/basic/base"
	"time"
)

//Listen 触发监听入口
func Listen(portName string) {
	portRW := utils.FindPortRw(portName)
	if portRW != nil {
		defer func(portRW io.ReadWriteCloser) {
			err := portRW.Close()
			if err != nil {
				log.Fatal(" port close failed ")
			}
		}(portRW)
		for {
			//由于灵敏度过高 进行读取延迟 两次读取 并将结果合并
			//todo 该灵敏度可设置
			first := read(portRW, 4, 8)
			time.Sleep(time.Duration(base.Properties.ReadSensitivity))
			delay := read(portRW, 8, 16)
			result := append(first, delay...)
			base.Logger.Info().Printf(" [%s] >> %X \n", portName, result)
			//todo 对结果的逻辑处理

			//todo 另一个灵敏度调节
			time.Sleep(time.Duration(base.Properties.ReadSensitivity * 2))
		}
	}
}

func read(portRW io.ReadWriteCloser, byteLen int, byteCap int) []byte {
	bytes := make([]byte, byteLen, byteCap)
	read, err := portRW.Read(bytes)
	if err != nil {
		log.Println(" port read failed ")
	}
	return bytes[:read]
}
